# coding:utf-8
"""
    @author : 计祝兵
    @date : 2024/6/3 15:47
    @file : save_word.py
    @desc : 生成world文件并保存
"""
from docx import Document
from docx.shared import Inches, RGBColor, Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT, WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE

# 定义一个doc
doc = Document()

for i in doc.styles:
    if i.type == WD_STYLE_TYPE.TABLE:
        print(i.name)

# 设置样式
style = doc.styles['Normal']
style.font.name = '微软雅黑'
# 字体大小
style.font.size = Pt(16)

# 标题相关设置
title = doc.add_heading('', 0)
# 标题居中
title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# 标题的字体大小
title.style.font.size = Pt(22)
# 标题的内容
_t = title.add_run('My Title \n 123')
# 斜体
_t.italic = True
# 加粗
_t.bold = True
# 下划线
_t.underline = True

# 设置段落相关的内容和样式
p = doc.add_paragraph("I am studying python,我们一起共创未来！")
p.add_run("\n 首先肯定还是要从基础学起，且不可好高骛远").italic = True
p.add_run('后面就会发现Python越学越有意思')
# 设置段落居中
p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

# 继续添加一个新的段落,放图片
p1 = doc.add_paragraph()
p1.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
_p1 = p1.add_run()

# 添加图片
image = _p1.add_picture('logo2020.png', width=Inches(2), height=Inches(2))

# 添加表格
title = ['name', 'age', 'sex']

# 设置表格
table = doc.add_table(rows=1, cols=3, style='Colorful Shading Accent 6')
title_cells = table.rows[0].cells
title_cells[0].text = title[0]
title_cells[1].text = title[1]
title_cells[2].text = title[2]

data = [
    ('xiaoming', '20', '男'),
    ('xiaoLi', '22', '男'),
    ('xiaoHong', '18', '女')
]

for d in data:
    rows_cell = table.add_row().cells
    rows_cell[0].text = d[0]  # name
    rows_cell[1].text = d[1]  # age
    rows_cell[2].text = d[2]  # sex

# 新增一个分页
doc.add_page_break()
# 新增的一页中再添加一个标题
doc.add_heading('my title 2', 0)

doc.save('test.docx')
